<template>
  <div>
  <div class="wrap">
	   <audio id="audioMusic" src="@/views/message/audio/notify.mp3"  hidden="true" ref="audio"></audio>
  </div>
    <el-dropdown @command="handleCompanyChange" ref="dropdown" trigger="click">
      <div class="badge">
        <el-badge :hidden="noticeNum==0" :value="noticeNum" class="item" >
          <i class="el-icon-bell" />
        </el-badge>
      </div>
      <el-dropdown-menu slot="dropdown" class="menu">
        <el-tabs v-model="activeName" @tab-click="handleClick" stretch>
          <el-tab-pane label="通知消息" name="notify">
            <el-dropdown-item
              v-for="(i, index) in notice"
              :key="index"
              :command="i"
            >
              <div class="box">
                <span>{{ i.titile }}</span>
                <span>{{ i.priority }}</span>
              </div>
              <div>{{ i.sendTime + "发布" }}</div>
            </el-dropdown-item>
          </el-tab-pane>
          <el-tab-pane label="系统消息" name="information">
            <el-dropdown-item
              v-for="(i, index) in information"
              :key="index"
              :command="i"
            >
              <div class="box">
                <span>{{ i.titile }}</span>
                <span>{{ i.priority }}</span>
              </div>
              <div>{{ i.sendTime + "发布" }}</div>
            </el-dropdown-item>
          </el-tab-pane>
        </el-tabs>
        <el-button plain @click="more" class="button">查看更多</el-button>
      </el-dropdown-menu>
    </el-dropdown>

    <el-dialog :title="title" :visible.sync="open" width="40%">
      <el-divider></el-divider>
      <div><div class="titileBox">{{ titile }}</div></div>
      <el-divider></el-divider>
      <div>{{ "发布人：" + sender + "  " + "发布时间：" + sendTime }}</div>
      <el-divider></el-divider>
      <div v-html="msgContent">{{ msgContent }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { publishAnnouncement } from "@/views/message/js/announcement.js";
import { getUserProfile } from "@/api/system/user";
import {readStatus} from '@/views/message/js/send.js'

import store from '@/store/'

export default {
  data() {
    return {
      activeName: "notify",
      // 通知消息
      notice: [],
      // 系统消息
      information: [],
      open: false,
      title: "",
      titile: "",
      sender: "",
      sendTime: "",
      msgContent: "",
      userId: "",
      noticeNum: 0
    };
  },
  created() {
    getUserProfile().then(response => {
      var user = response.data;
	  console.log("user",user)
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      this.userId = user.userId;
      this.getNews();
      this.initWebSocket();
    });
  },
  mounted(){
    // 接收事件总线
    this.$EventBus.$on("informationClick",(res)=>{
      this.getNews()
    })
  },
  destroyed(){
    // 页面销毁时移除事件总线
    this.$EventBus.$off("notifyClick")
  },
  methods: {
    handleClick(tab, event) {},
    // 查看更多按钮
    more() {
      if (this.$route.path != "/message/information") {
        this.$router.replace({ name: "Information" });
        this.$refs.dropdown.visible = false;
      } else {
        this.$message("当前已在此页面");
        this.$refs.dropdown.visible = false;
      }
    },
    // 确定按钮
    dialogVisible() {
      this.open = false;
    },
    getNews() {
      publishAnnouncement(store.getters.userInfo.userId).then((res) => {
        if (res.code == 200) {
          this.noticeNum = res.data.anntMsgTotal + res.data.sysMsgTotal;
          this.notice = res.data.sysMsgList
          this.information = res.data.anntMsgList
        }
      });
    },
    handleCompanyChange(command) {
		  console.log("!!!!播放")
      this.open = true;
      let anntId = command.id;
      // let userId = store.getters.userInfo.userId
      console.log(anntId);
      console.log(userId);
      readStatus(anntId).then((res) =>{
        if (res.code == 200) {
          this.$EventBus.$emit("notifyClick")
          this.getNews()
        }
      })
      if (command.msgCategory == 1) {
        this.title = "通知消息";
      }else if (command.msgCategory == 2) {
        this.title = "系统信息";
      }
      this.titile = command.titile;
      this.sender = command.sender;
      this.sendTime = command.sendTime;
      this.msgContent = command.msgContent;
    },
    initWebSocket: function() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = this.userId;
      console.log(
        "process.env.VUE_APP_API_BASE_URL=" + process.env.VUE_APP_API_BASE_URL
      );
      var url = process.env.VUE_APP_API_BASE_URL.replace("https://","wss://").replace("http://","ws://")+"/message/websocket/"+userId;
      // var url = "ws://localhost:8080/message/websocket/" + userId;
      console.log(url);
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
    },
    websocketOnopen: function() {
      console.log("WebSocket连接成功");
      //心跳检测重置
      // this.heartCheck.reset().start();
    },
    websocketOnerror: function(e) {
      console.log("WebSocket连接发生错误");
      this.reconnect();
    },
    websocketOnmessage: function(e) {
      console.log("-----接收消息-------", e.data);
      this.$refs.audio.currentTime = 0;
      this.$refs.audio.play();
      var data = eval("(" + e.data + ")"); //解析对象
      if (data.cmd == "topic") {
        //系统通知
        this.getNews();
      } else if (data.cmd == "user") {
        //用户消息
        this.getNews();
      }
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnclose: function(e) {
      console.log("WebSocket连接关闭");
      console.log("connection closed ", e);
      if (e) {
        console.log("connection closed (" + e.code + ")");
      }
      this.reconnect();
    },
    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text);
      } catch (err) {
        console.log("send failed (" + err.code + ")");
      }
    },
    reconnect() {
      var that = this;
      if (that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function() {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    }
  }
};
</script>

<style scoped>
.el-icon-bell {
  font-size: 25px;
}
.menu {
  width: 200px;
}
.button {
  width: 180px;
  margin: 10px;
}
.item {
  margin-top: 4px;
  margin-right: 6px;
}
.badge {
  width: 20px;
  margin-right: 10px;
}
.box {
  display: flex;
  justify-content: space-between;
}
.titileBox{
  margin: 0 auto;
  text-align: center;
  font-weight: bold;
}
</style>
